package 二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层序遍历 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<List<Integer>> resList = new ArrayList<List<Integer>>();

        public List<List<Integer>> levelOrder(TreeNode root) {
            //checkFun01(root,0);
            checkFun02(root);

            return resList;
        }


        //DFS-递归方式
        public void checkFun01(TreeNode node, Integer deep) {
            if (node == null) return;
            deep++;
            if (resList.size()<deep){
                //当层级增加时，list的Item也增加，利用list的索引值进行层级界定
                ArrayList<Integer> item = new ArrayList<>();
                resList.add(item);
            }
            resList.get(deep-1).add(node.val);
            checkFun01(node.left,deep);
            checkFun01(node.right,deep);
        }

        public void checkFun02(TreeNode node){
            if (node==null) return;
            Queue<TreeNode> que = new LinkedList<>();
            que.offer(node);
            while(!que.isEmpty()){
                ArrayList<Integer> list = new ArrayList<>();
                int size = list.size();
                while(size>0){
                    TreeNode poll = que.poll();
                    list.add(poll.val);
                    if (poll.left!=null) que.offer(poll.left);
                    if (poll.right!=null) que.offer(poll.right);
                    size--;
                }
                  resList.add(list);
            }
        }
    }
}
